package com.gx.rbac.springsecurityrbac.entity;

import com.baomidou.mybatisplus.enums.IdType;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 用户表
 * </p>
 *
 * @author GX
 * @since 2017-08-28
 */
@Data
@TableName("sys_user")
public class User extends Model<User>  implements UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
	@TableId(value="id", type= IdType.AUTO)
	private Long id;
    /**
     * 用户名
     */
	private String username;
    /**
     * 密码  加密
     */
	private String password;
    /**
     * 昵称
     */
	@TableField("nice_name")
	private String niceName;
    /**
     * 头像
     */
	private String avatar;
    /**
     * 注册时间
     */
	@TableField("create_time")
	private Date createTime;
    /**
     * 最后上线时间
     */
	@TableField("last_time")
	private Date lastTime;
    /**
     * 最后上线IP地址
     */
	@TableField("last_open_ip")
	private String lastOpenIp;
    /**
     * 用户状态  0 正常  1 封号 
     */
	private Integer status;

	// 用户对应的 角色列表
	private List<Role> roles;



	@Override
	protected Serializable pkVal() {
		return this.id;
	}



	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		//  需将 List<Authority> 转成 List<SimpleGrantedAuthority>，否则前端拿不到角色列表名称
		List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
		for(GrantedAuthority authority : this.roles){
			simpleAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
		}
		return simpleAuthorities;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
